<template>
  <div
    :class="{
      'search-box': true,
      hide:
        showType == 'campus' || showType == 'civil' || showType == 'company',
      short: showJobSearchSelect,
    }"
    :style="{ 'margin-top': marginTop, height: height }"
  >
    <el-select
      v-model="showTypeSelectValue"
      class="jobSearchSelect"
      @change="changeShowTypeSelect"
      v-if="showJobSearchSelect"
      popper-class="JobSearchSelectPopper"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
      <div slot="prefix" class="jobSearchSelectPrefix">
        <img :src="searchBoxSwitchIcon" alt="" />
      </div>
    </el-select>
    <div class="searchBoxInner">
      <div
        :class="{
          hide:
            showType == 'campus' ||
            showType == 'civil' ||
            showType == 'company',
        }"
        class="positionSearchContainer"
      >
        <el-input
          v-if="!searchClick && inputData == ''"
          class="search"
          placeholder="输入职业关键词，查看职业概况"
          prefix-icon="el-icon-search"
          @focus="searchFocus"
          v-model="inputData"
          @click.stop="
            () => {
              return;
            }
          "
        >
        </el-input>
        <el-autocomplete
          v-else
          :debounce="0"
          id="searchInput"
          class="search searchBlue"
          placeholder=""
          @focus="searchFocus"
          @select="inputSelect"
          @keyup.enter.native="enterSelect"
          v-model="inputData"
          :fetch-suggestions="querySearchAsync"
          ref="greenFocus"
          :trigger-on-focus="true"
          :popper-class="noData ? 'platform-auto-complete' : ''"
          value-key="positionName"
          clearable
        >
          <el-button slot="append" class="searchButton" @click.stop="search">
            搜索</el-button
          >
          <template slot-scope="{ item }">
            <div class="itemNameContainer" v-if="!noData">
              <div v-html="formateText(item.positionName)"></div>
              <div class="otherName" v-if="item.otherName">
                其他名称：<span v-html="formateText(item.otherName)"></span>
              </div>
            </div>
            <div
              class="emptyItem"
              @click="handleEmptyItemClick(item)"
              v-if="noData"
            >
              {{ item.default }}
              <span class="reportText" v-if="item.default == '暂无匹配职业'"
                >立即反馈 ></span
              >
            </div>
          </template>
        </el-autocomplete>
        <div
          class="historyWords"
          v-if="historyWords.length > 0 && !hideHistory"
        >
          <div
            class="wordsItem"
            v-for="(item, index) in historyWords"
            :key="index"
            :title="item"
            @click="clickHistory(item)"
          >
            {{ item }}
          </div>
          <div class="wordsItemDelete" @click="deleteAllHistory">
            <i class="el-icon-delete"></i>
          </div>
        </div>
      </div>
      <div class="jobSearchContainer" v-if="showJobSearch">
        <!-- 下面的是搜岗位的，以防万一还是保留 -->
        <!-- <el-input v-if="!searchClick && matchZpName == ''" class="search" placeholder="输入职业关键词，查看职业概况"
          prefix-icon="el-icon-search" @focus="searchFocus" v-model="matchZpName" @click.stop="
        () => {
          return;
        }
      ">
        </el-input>
        <el-autocomplete v-else :debounce="0" id="searchInput" class="search searchBlue" placeholder=""
          @focus="searchFocus" @select="inputSelect" @keyup.enter.native="enterSelect" v-model="matchZpName"
          :fetch-suggestions="jobQuerySearchAsync" ref="greenFocus" :trigger-on-focus="true"
          :popper-class="noData ? 'platform-auto-complete' : ''" value-key="positionName" clearable>
          <el-button slot="append" class="searchButton" @click.stop="search">
            搜索</el-button>
          <template slot-scope="{ item }">
            <div v-html="formateText(item.jtzw)"></div>
            {{ noData ? item.default : "" }}
          </template>
        </el-autocomplete> -->
        <el-input
          v-if="!searchClick && inputData == ''"
          class="search"
          placeholder="输入职业关键词，查看职业概况"
          prefix-icon="el-icon-search"
          @focus="searchFocus"
          v-model="inputData"
          @click.stop="
            () => {
              return;
            }
          "
        >
        </el-input>
        <el-autocomplete
          v-else
          :debounce="0"
          id="searchInput"
          class="search searchBlue"
          placeholder=""
          @focus="searchFocus"
          @select="inputSelect"
          @keyup.enter.native="enterSelect"
          v-model="inputData"
          :fetch-suggestions="querySearchAsync"
          ref="greenFocus"
          :trigger-on-focus="true"
          :popper-class="noData ? 'platform-auto-complete' : ''"
          value-key="positionName"
          clearable
        >
          <el-button slot="append" class="searchButton" @click.stop="search">
            搜索</el-button
          >
          <template slot-scope="{ item }">
            <div v-html="formateText(item.positionName)"></div>
            {{ noData ? item.default : "" }}
          </template>
        </el-autocomplete>
      </div>
    </div>
    <reportRequestPositionDialog
      v-if="reportRequestPositionDialogVisible"
      :dialogVisible.sync="reportRequestPositionDialogVisible"
    />
  </div>
</template>

<script>
import reportRequestPositionDialog from "./reportRequestPositionDialog.vue";
import searchBoxSwitchIcon from "@/assets/home/searchBoxSwitchIcon.png";
import { throttle } from "lodash";
import antiShake from "../../../utils/antiShake.js";
import { matchPositionList, campusJobSearch } from "@/api/home.js";
import jobSearchInputSwitchIcon from "@/assets/home/jobSearchInputSwitchIcon.png";
export default {
  props: {
    hideHistory: {
      type: Boolean,
      default: false,
    },
    marginTop: {
      type: String,
      default: "28px",
    },
    height: {
      type: String,
      default: "82px",
    },
  },
  components: {
    reportRequestPositionDialog,
  },
  data() {
    return {
      reportRequestPositionDialogVisible: false,
      searchBoxSwitchIcon,
      showTypeSelectValue: "campus",
      inputData: "",
      matchZpName: "",
      searchClick: false,
      automatedList: [{ default: "输入职业进行搜索" }],
      historyWords: [],
      noData: true, // 是否匹配到数据了
      throttledScroll: "",
      showJobSearch: false,
      showJobSearchSelect: false,
      options: [
        { label: "校招岗位", value: "campus" },
        { label: "专业匹配职业", value: "position" },
        { label: "考公岗位", value: "civil" },
      ],
      jobSearchInputSwitchIcon,
    };
  },
  computed: {
    showType() {
      const showType = this.$store.state.settings.showType;
      //showTypeSelectValue是选择框控制的值，目前是没什么用
      this.showTypeSelectValue = showType;
      //切换的时候如果显示了选择框就说明现在是有滚动的状态，也要展示输入框
      if (
        this.showJobSearchSelect &&
        (showType == "campus" || showType == "civil" || showType == "company")
      ) {
        this.showJobSearch = true;
      }
      return showType;
    },
  },
  mounted() {
    // window.addEventListener("scroll", this.onScroll);

    if (this.$route.query.SecretKey || localStorage.getItem("SecretKey")) {
      let SecretKey =
        this.$route.query.SecretKey || localStorage.getItem("SecretKey");
      //河南测绘学院隐藏校招岗位
      if (SecretKey == "94cbe78f3bcec8be756042d1554c13b5") {
        this.options = [{ label: "专业匹配职业", value: "position" }];
      }
      // 校园体验版本增加考公岗位
      // if (SecretKey == "94cbe78f3bcec8be2a4b0ac87a31ba7c") {
      //   this.options = [...this.options, { label: "考公岗位", value: "civil" }];
      // }
      if (SecretKey == "94cbe78f3bcec8be2a4b0ac87a31ba7c") {
        this.options = [
          ...this.options,
          { label: "企业分析", value: "company" },
        ];
      }
      if (SecretKey == "94cbe78f3bcec8be98fe617690abeb1e") {//深圳技术大学
        this.options = [{ label: "专业匹配职业", value: "position" }, { label: "校招岗位", value: "campus" }];
      }
    }

    const historyWords = localStorage.getItem("historyWords");
    if (historyWords) {
      this.historyWords = JSON.parse(localStorage.getItem("historyWords"));
      this.$nextTick(() => {
        this.historyWordsMax();
      });
    } else {
      this.historyWords = [];
    }

    this.throttledScroll = throttle(() => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      //展示招聘输入框的条件
      if (
        scrollTop > 120 &&
        (this.showType == "campus" ||
          this.showType == "civil" ||
          this.showType == "company")
      ) {
        // console.log("展示新的输入框吧");
        this.showJobSearch = true;
      } else {
        // console.log("隐藏输入框");
        this.showJobSearch = false;
      }
      //展示选择框的条件
      if (scrollTop > 120) {
        // console.log("----------->展示选择框的条件",this.showType,scrollTop);
        this.showJobSearchSelect = true;
      } else {
        // console.log("----------->隐藏选择框的条件",this.showType,scrollTop);
        this.showJobSearchSelect = false;
      }
    }, 200); // 每200毫秒触发一次
    window.removeEventListener("scroll", this.throttledScroll);
    window.addEventListener("scroll", this.throttledScroll);
  },
  methods: {
    handleEmptyItemClick(item) {
      if (item.default == "暂无匹配职业") {
        this.reportRequestPositionDialogVisible = true;
      }
    },
    changeShowTypeSelect(value) {
      this.$store.dispatch("settings/changeSetting", {
        key: "showType",
        value: value,
      });
      this.showJobSearch = false;
      this.searchClick = false;
    },
    clickHistory(item) {
      this.inputData = item;
      this.changeSelect(function (item) {
        console.log(item);
      });
    },
    deleteAllHistory() {
      this.historyWords = [];
      localStorage.setItem("historyWords", []);
    },
    search() {
      this.$refs.greenFocus.activated = false;
      if (this.inputData != "") {
        this.searchByInputData();
        console.log(this.automatedList);
        if (this.automatedList[0].ylPositionId) {
          this.routerToDetail(this.automatedList[0]);
        }
      }
    },
    searchByInputData() {
      if (!this.inputData.match(/^[ ]*$/)) {
        this.$emit("getInputData", this.inputData);
        let index = this.historyWords.indexOf(this.inputData);
        if (index >= 0) {
          this.historyWords.splice(index, 1);
        }
        this.historyWords.unshift(this.inputData);
        this.$nextTick(() => {
          this.historyWordsMax();
        });
      }
    },
    searchFocus() {
      this.searchClick = true;
      setTimeout(() => {
        this.$refs.greenFocus.focus();
      }, 200);
    },
    //点击搜索框之外，判断搜索框类型
    clickInputOutside() {
      // if (this.searchClick) {
      //   this.$refs.greenFocus.activated = false;
      // }
      // //console.log("this.inputData", this.inputData);
      if (this.inputData == "") {
        this.searchClick = false;
      }
    },
    //失去焦点，收回下拉框
    // CollapseDropdownBox() {
    //   setTimeout(() => {
    //     this.$refs.greenFocus.activated = false;
    //   }, 100);
    // },
    inputSelect(e) {
      if (e.ylPositionId) {
        this.routerToDetail(e);
      }
    },
    enterSelect() {
      if (this.inputData == "") {
        return;
      } else {
        this.search();
      }
    },
    routerToDetail(e) {
      let routeData = this.$router.resolve({
        path: "/position-detail",
        query: {
          // fatherTitle: `${e.topTitle} · ${e.parentTitle}`,
          id: e.ylPositionId,
          name: e.positionName,
          superToken: this.$route.query.superToken || "",
          SecretKey: this.$route.query.SecretKey || "",
          customerName: this.$route.query.customerName,
        },
      });
      window.open(routeData.href, "_blank");
      this.searchByInputData();
    },
    jobQuerySearchAsync(queryString, cb) {
      if (this.matchZpName == "") {
        this.automatedList = [{ default: "输入职业关键词，查看职业概况" }];
        cb([{ default: "输入职业关键词，查看职业概况" }]);
      } else {
        if (queryString) {
          antiShake(() => {
            this.jobChangeSelect(cb);
          }, 1000).call(this);
        } else {
          cb([{ default: "输入职业关键词，查看职业概况" }]);
        }
      }
    },
    jobChangeSelect(cb) {
      //这里获取联想的数据列表
      if (this.matchZpName != "") {
        campusJobSearch({
          matchZpName: this.matchZpName, //搜索关键字
          pageNo: 1,
          pageSize: 10,
        }).then((res) => {
          if (res.code == 200) {
            this.automatedList = res.data;
            if (this.automatedList.length == 0) {
              this.automatedList = [{ default: "暂无匹配岗位" }];
              this.noData = true;
            }
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              "this.automatedList即将输出", this.automatedList;
              cb(this.automatedList);
            }, 100);
          }
        });
      }
    },
    querySearchAsync(queryString, cb) {
      if (this.inputData == "") {
        this.automatedList = [{ default: "输入职业进行搜索" }];
        cb([{ default: "输入职业进行搜索" }]);
      } else {
        if (queryString) {
          antiShake(() => {
            //console.log("调用");
            this.changeSelect(cb);
          }, 1000).call(this);
        } else {
          cb([{ default: "输入职业关键词，查看职业概况" }]);
        }
      }
    },
    changeSelect(cb) {
      //这里获取联想的数据列表
      if (this.inputData != "") {
        matchPositionList({
          matchTitle: this.inputData,
        }).then((res) => {
          if (res.code == 200) {
            this.automatedList = res.data;
            if (this.automatedList.length == 0) {
              this.automatedList = [{ default: "暂无匹配职业" }];
              this.noData = true;
            } else {
              this.noData = false;
            }
            //console.log("this.automatedList11", this.automatedList);
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              "this.automatedList即将输出", this.automatedList;
              cb(this.automatedList);
            }, 100);
          }
        });
      }
    },
    formateText(content) {
      if (content && content != "") {
        let text = this.inputData;
        let regStr = `(${text})`;
        let reg = new RegExp(regStr, "g");
        // 正则替换，关键词飘红
        return content.replace(
          reg,
          '<span style="color:#0B6EFF;">' + text + "</span>"
        );
      }
    },
    historyWordsMax() {
      const el = document.getElementsByClassName("wordsItem");
      let totalWidth = 0;
      el.forEach((item, index) => {
        totalWidth += item.clientWidth;
        if (totalWidth >= 500) {
          if (index != 0) {
            this.historyWords.pop();
          } else {
            let history = document.getElementsByClassName("wordsItem")[0];
            history.style.overflow = `hidden`;
            history.style.whiteSpace = `nowrap`;
            history.style.textOverflow = `ellipsis`;
          }
          return;
        }
      });
      localStorage.setItem("historyWords", JSON.stringify(this.historyWords));
    },
  },
  destroy() {
    window.removeEventListener("scroll");
  },
};
</script>

<style scoped lang="scss">
.jobSearchSelect {
  // padding-left: 10px;
  margin-right: 8px;
  ::v-deep .el-input__inner {
    background: rgba(76, 149, 255, 0.2);
    box-shadow: 0px -1px 14px 0px rgba(14, 30, 108, 0.6);
    border-radius: 21px;
    border-image: linear-gradient(
        180deg,
        rgba(94, 109, 132, 1),
        rgba(121, 136, 159, 1)
      )
      1 1;
    backdrop-filter: blur(1.5px);
    border: 1px solid #73829a;
    text-align: center;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 14px;
    color: #ffffff;
    line-height: 20px;
  }
  ::v-deep .el-input__prefix {
    display: flex;
    align-items: center;
    left: 42px;
    .jobSearchSelectPrefix {
      font-size: 0;
      img {
        width: 24px;
        height: 24px;
      }
    }
  }
}
.search-box {
  width: 100%;
  margin-top: 25px;
  margin-bottom: 18px;
  display: flex;
  justify-content: center;
  position: sticky;
  top: 11px;
  // height: 82px; //如果不想抖就要给高度
  z-index: 7; //很重要别乱改
  transition: all 0.3s ease-in-out;
  &.hide {
    height: 0;
  }
  &.short {
    .search {
      width: 334px;
    }
  }
  .positionSearchContainer {
    transition: all 0.3s ease-in-out;
    height: 82px;
    opacity: 1;
    overflow: hidden;
    &.hide {
      height: 0;
      opacity: 0;
    }
  }
  .search {
    width: 600px;
    z-index: 2;
    ::v-deep .el-input__inner {
      background: rgba(205, 228, 255, 0.2);
      box-shadow: 0px 2px 10px 0px rgba(14, 30, 108, 0.5);
      border-radius: 21px;
      border: 1px solid rgba(94, 109, 132, 1);
      // border-image: linear-gradient(180deg, , rgba(121, 136, 159, 1)) 1 1;
      backdrop-filter: blur(1.5px);
      &::placeholder {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #a8b7d2;
        line-height: 20px;
        text-align: left;
        font-style: normal;
        padding-left: 24px;
      }
    }
    ::v-deep .el-input__prefix {
      left: 23px;
    }
    ::v-deep .el-icon-search:before {
      font-size: 17px;
    }
    ::v-deep .el-input__inner {
    }
  }
  .searchBlue {
    z-index: 2;
    ::v-deep .el-input__inner {
      border: #0b6eff 2.5px solid;
      border-radius: 21px 0 0 21px;
      background: #fff;
      transition: 0.5s;
      padding-left: 20px;
    }

    ::v-deep .el-input__inner:focus {
      border-radius: 21px 0 0 0px;
      border-bottom: 1px;
      transition: 0s;
    }
    .searchButton {
      background: #0b6eff;
      color: #fff;
      width: 88px;
      border-radius: 0 21px 21px 0;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      letter-spacing: 5px;
      height: 40px;
    }
    ::v-deep .el-input-group__append,
    .el-input-group__prepend {
      background: none;
      border: none;
    }
  }
  .historyWords {
    width: 600px;
    position: relative;
    padding: 10px 20px;
    margin-right: 20px;
    display: flex;
    // overflow: hidden;
    // text-overflow: ellipsis;
    .wordsItem {
      color: #a8b7d2;
      font-size: 14px;
      background: rgba(0, 0, 0, 0.15);
      padding: 3px 10px;
      border-radius: 6px;
      margin: 0 5px;
      cursor: pointer;
      max-width: 560px;
      white-space: nowrap;
    }
    .wordsItemDelete {
      color: #bfbfbf;
      font-size: 14px;
      background: rgba(0, 0, 0, 0.15);
      padding: 3px 10px;
      border-radius: 6px;
      margin: 0 5px;
      cursor: pointer;
    }
  }
}
.itemNameContainer {
  display: flex;
  .otherName {
    margin-left: 20px;
    color: #9cabb7;
  }
}
.jobSearchContainer {
}
.emptyItem {
  .reportText {
    float: right;
    color: #0b6eff;
  }
}
// .historyWords::-webkit-scrollbar {
//   width: 0 !important;
// }
// /*IE 10+*/
// .historyWords {
//   -ms-overflow-style: none;
// }
// /*Firefox*/
// .historyWords {
//   overflow: -moz-scrollbars-none;
// }
</style>
<style>
.el-popper[x-placement^="bottom"] {
  margin-top: 0px;
}
.el-autocomplete-suggestion {
  margin: 0px;
  border: #0b6eff 2.5px solid;
  border-top: 0px solid;
  border-radius: 0 0 21px 21px;
  transition: 0s;
  box-shadow: none;
}
.el-autocomplete-suggestion::before {
  content: "";
  display: inline-block;
  width: 94%;
  height: 1px;
  background: #e9e9e9;
  position: absolute;
  top: 0px;
  left: 3%;
  border-radius: 8px;
}
/* .el-autocomplete-suggestion li:hover::after {
  content: "点击或回车进入详情页";
  position: absolute;
  top: 0px;
  right: 10px;
  font-size: 12px;
} */
.el-autocomplete-suggestion li:hover {
  position: relative;
  margin: 0 10px;
}

/* 消除小三角 */
.el-popper[x-placement^="bottom"] .popper__arrow {
  border: none;
}
.el-popper[x-placement^="bottom"] .popper__arrow::after {
  border: none;
}
</style>
